﻿@page "/exportpdf"
@using MaBlaApp.Data
@inject WeatherForecastService ForecastService
@implements IAsyncDisposable
@inject IJSRuntime JS

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <div class="m-2">
        <button class="btn btn-primary col-6" @onclick=ExportHtml2PdfForPreview>从html导出pdf</button>
    </div>

    <div id=@weatherRootId class="m-2" style="overflow-y:auto">

        <h4 class="text-center">天气预报一览表</h4>

        <table class="table">
            <thead>
                <tr>
                    <th>日期</th>
                    <th>气温. (C)</th>
                    <th>气温. (F)</th>
                    <th>预报</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var forecast in forecasts)
                {
                    <tr>
                        <td>@forecast.Date.ToShortDateString()</td>
                        <td>@forecast.TemperatureC</td>
                        <td>@forecast.TemperatureF</td>
                        <td>@forecast.Summary</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
}

<textarea class="m-2" style="height:100px;" @bind=message></textarea>

<ModalComponent @ref="modal">
    <Title>预览报告</Title>
    <Body>
        <iframe id=@previewReportId style="width:100%;height:100%" type='application/pdf' />
    </Body>
    <Footer>
        @* <button type="button" class="btn btn-primary">保存</button> *@
        <button type="button" class="btn btn-secondary" data-dismiss="modal" @onclick="() => modal.Close()">Close</button>
    </Footer>
</ModalComponent>

@code {
    private WeatherForecast[] forecasts;
    private IJSObjectReference? module;
    private const string weatherRootId = "weatherRoot";
    private const string previewReportId = "previewReport";
    private ModalComponent modal;
    private string message = $"MAUI Blaor";
    private DotNetObjectReference<ExportPdf>? InstanceRazor;

    protected override async Task OnInitializedAsync()
    {
        forecasts = await ForecastService.GetForecastAsync(DateTime.Now, 50);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        base.OnAfterRender(firstRender);

        if (firstRender)
        {
            InstanceRazor = DotNetObjectReference.Create(this);

            module = await JS.InvokeAsync<IJSObjectReference>("import", "./js/exportpdf.js");
        }
    }

    //预览html导出pdf
    private async Task ExportHtml2PdfForPreview()
    {
        try
        {
#if WINDOWS

    //在html元素预览，适用于windows
    await module!.InvokeVoidAsync("exportHtml2PdfForPreview", weatherRootId, previewReportId, null);

    modal.Open();

#endif

#if ANDROID

    #region 方案1

    //回调razor页面函数，获取pdf字符串，适用于安卓
    await module!.InvokeVoidAsync("exportHtml2PdfForPreview", weatherRootId, null, InstanceRazor);

    #endregion

    #region 方案2

    //  var jsStreamRef = await module!.InvokeAsync<IJSStreamReference>("convertHtml2PdfAry", weatherRootId);

    // //读取JavaScript文件流，默认512k字节！改到10M字节
    // using var jsStream = await jsStreamRef.OpenReadStreamAsync(10 * 1024 * 1024);

    // //创建缓存pdf文件
    // string filePath = Path.Combine(FileSystem.Current.CacheDirectory, "report.pdf");

    // using (var fs = File.OpenWrite(filePath))
    // {
    // await jsStream.CopyToAsync(fs);
    // }

    //  await OpenPdf(filePath);

    #endregion

#endif

        }
        catch (Exception ex)
        {
            message = $"ExportHtml2PdfForPreview出错: {ex.Message}";
        }

        await InvokeAsync(() => StateHasChanged());
    }

    //获取pdf字符串，用于JavaScript回调razor页面函数
    [JSInvokable]
    public async Task GetPdfBase64String(string base64String)
    {
        var ary = Convert.FromBase64String(base64String);

        string filePath = Path.Combine(FileSystem.Current.CacheDirectory, "report.pdf");

        await File.WriteAllBytesAsync(filePath, ary);

        await OpenPdf(filePath);
    }

    //调用安卓系统关联pdf类型的APP去打开pdf文件
    private async Task OpenPdf(string filePath)
    {
        //用操作系统配套的APP打开pdf文件
        //https://learn.microsoft.com/zh-cn/dotnet/maui/platform-integration/appmodel/launcher?view=net-maui-7.0&tabs=android
        await Launcher.Default.OpenAsync(new OpenFileRequest("打开pdf", new ReadOnlyFile(filePath)));
    }

    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        if (module is not null)
        {
            await module.DisposeAsync();
        }
    }

}
